import router from './router'
import store from './store'
import { Message } from 'element-ui'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import { getToken, removeToken } from '@/utils/auth' // get token from cookie
// import getPageTitle from '@/utils/get-page-title'

NProgress.configure({ showSpinner: false }) // NProgress Configuration

const whiteList = ['/login', '/404'] // no redirect whitelist

router.beforeEach(async(to, from, next) => {
  const hasToken = getToken()

  if (hasToken) {
    if (store.getters.userInfo) {
      // 刷新/重新打开userInfo没了，这里空得eslint会报错
    } else {
      try {
        // 重新请求一下userInfo
        await store.dispatch('user/reqUserInfo')
      } catch (error) {
        // token过期
        removeToken()
        Message.warning('请重新登录')
        next(`/login?redirect=${to.path}`)
      }
    }
    // 登录的情况下不再访问登录页
    if (to.path === '/login') {
      Message.warning('你已登录')
      next('/')
    }
    next()
  } else {
    // 没token得
    if (whiteList.includes(to.path)) {
      next()
    } else {
      Message.warning('请先登录')
      // 在路径中记录从哪来，等会返回这个页面
      next(`/login?redirect=${to.path}`)
    }
  }
})
router.afterEach(() => {
  // finish progress bar
  NProgress.done()
})
